﻿using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class UtilCameraSelector : MonoBehaviour {

	//public Camera[] cameras;
	public Camera currentCamera;
	public GameObject target;
	public GameObject targetFindRoot;

	public bool changeTargetAuto = false; public void setChangeTargetAuto(Toggle t) {
		changeTargetAuto = t.isOn;if (timerSlider != null) timerSlider.gameObject.SetActive(changeTargetAuto);
	}

	public float changeTargetAutoTime = 15;
	public float changeTargetAutoCounter = 0;

	public Slider timerSlider;

	void Start() {
		/*if (currentCamera == null) {
			currentCamera = gameObject.GetComponentInChildren<Camera>();
			currentCamera.gameObject.SetActive(true);
		}*/
		setCamera (gameObject.GetComponentInChildren<Camera>());
	}

	public void setCamera(Camera c) {
		if (currentCamera != null) {
			currentCamera.gameObject.SetActive(false);
		}
		currentCamera = c;
		currentCamera.gameObject.SetActive(true);

		UtilCameraFollowVehicle u = c.gameObject.GetComponent<UtilCameraFollowVehicle> ();
		if (u != null) {
			u.target = target;
		}
	}

	public void findNewTarget() {
		Vehicle[] vs = targetFindRoot.GetComponentsInChildren<Vehicle> ();
		int n = 0;
		foreach (Vehicle v in vs) {
			if (n * Random.Range (0, n) == 0) target = v.body.gameObject; n++;
		}	

		UtilCameraFollowVehicle u = currentCamera.gameObject.GetComponent<UtilCameraFollowVehicle> ();
		if (u != null) {
			u.target = target;
		}
	}

	public void FixedUpdate() {

		if (changeTargetAutoTime > 0 && changeTargetAuto) {
			changeTargetAutoCounter += Time.fixedDeltaTime;
			if (timerSlider != null) timerSlider.value = timerSlider.minValue + timerSlider.maxValue * (changeTargetAutoCounter / changeTargetAutoTime);
			if (changeTargetAutoCounter >= changeTargetAutoTime) {
				changeTargetAutoCounter -= changeTargetAutoTime;
				if (changeTargetAutoCounter >= changeTargetAutoTime) changeTargetAutoCounter = 0;
				findNewTarget ();
			}
		}
		if (target == null) {
			findNewTarget ();
			changeTargetAutoCounter = 0;
		}

	}

}
